package com.ruoyi.mall.mq;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.mall.constant.OrderPaymentQueueExchangeContant;
import com.ruoyi.mall.domain.OrderMessage;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;

@Component
public class SendService {
    @Autowired
    private AmqpTemplate amqpTemplate;


    @Value("-${spring.profiles.active}")
    private String profile;


    @Value("${rabbitmq.delayTimes}")
    private String delayTimes;

    /*public void sendMessage(String message) {
        *//**
         * 发送消息
         * 参数1：交换机名称
         * 参数2：RoutingKey
         * 参数3：具体发送的消息内容
         *//*
        amqpTemplate.convertAndSend(OrderPaymentQueueExchangeContant.ORDER_PAYMENT_EXCHANGE,OrderPaymentQueueExchangeContant.ORDER_PAYMENT_ROUTING,message);
    }

    public void sendFanout(String message) {
        amqpTemplate.convertAndSend("fanoutExchange","",message);
    }

    public void sendTopic(String message) {
        amqpTemplate.convertAndSend("topicExchange","aa.bb.cc",message);
    }*/

    /**
     *
     * @param message
     * @param time 单位分钟
     * @throws UnsupportedEncodingException
     */
    public void sendDelayMessage(String message,Integer time) throws UnsupportedEncodingException {
        Message msg = MessageBuilder.withBody((message).getBytes(StandardCharsets.UTF_8)).setHeader("x-delay", 1000L*60*time).build();
        amqpTemplate.convertAndSend(OrderPaymentQueueExchangeContant.ORDER_PAYMENT_EXCHANGE, OrderPaymentQueueExchangeContant.ORDER_PAYMENT_QUEUE+profile, msg);
    }

    @Async
    public void sendOrderMessage(Long orderId) throws UnsupportedEncodingException {
        Deque<Integer> delayQue = getDelayQue(delayTimes);
        Integer poll = delayQue.poll();
        OrderMessage orderMessage = new OrderMessage(delayQue,orderId);
        this.sendDelayMessage(JSONObject.toJSONString(orderMessage),poll);
    }

    public Deque<Integer> getDelayQue(String str) {
        // 原始字符串

        // 使用逗号分割字符串
        String[] numbersStr = str.split(",");

        // 创建一个 ArrayDeque
        Deque<Integer> deque = new ArrayDeque<>();

        // 将每个数字字符串转换为整数并添加到 ArrayDeque 中
        for (String numStr : numbersStr) {
            int number = Integer.parseInt(numStr);
            deque.add(number);
        }

        return deque;
    }
}
